<template>
<div>
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
<!--  neirong-->
  <el-card>
    <el-row>
      <!--        添加juese按钮-->
      <el-col :span="5">
        <el-button type="primary"  @click="addDialogVisible = true">添加角色</el-button>
      </el-col>
    </el-row>
<!--liebiao-->
    <el-table
      :data="rolesList" border stripe>
      <el-table-column type="expand" label="#">
        <template v-slot="scope">
          <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1, i1) in scope.row.children" :key="i1">
<!--            一级渲染q-->
            <el-col :span="5">
              <el-tag @close="removeRightByid(scope.row, item1.id)" closable>{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
<!--            二级渲染-->
            <el-col :span="19">
              <el-row :class="[i2 === 0 ? '' : 'bdtop','vcenter']" v-for="(item2, i2) in item1.children" :key="i2">
                <el-col :span="6">
                <el-tag type="success" closable @close="removeRightByid(scope.row, item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right" ></i>
                </el-col>
                <el-col :span="18">
                  <el-tag type="warning" :class="[i3 === 0 ? '' : 'bdtop','vcenter']" @close="removeRightByid(scope.row, item3.id)" v-for="(item3, i3) in item2.children" :key="item3.id" closable>
                    {{ item3.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
      </template>
      </el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
      <el-table-column label="操作" width="300px" >
        <template v-slot="scope">
          <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
            <el-button type="primary" icon="el-icon-edit" size="mini"  @click="showRoleDialog(scope.row.id)">编辑</el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top"  :enterable="false">
            <el-button type="danger" icon="el-icon-delete" @click="removeRole(scope.row.id)" size="mini">删除</el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="分配权限" placement="top"  :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini"   @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
<!--    修改用户角色-->
    <el-dialog
      title="修改用户角色"
      :visible.sync="editDialogVisible"
      width="50%" >
      <!--      内容-->
      <el-form :model="editRolesForm" :rules="roleNameRules" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editFormInfo">确 定</el-button>
  </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" @close="addDislogClosed">
      <el-form :model="addRolesForm" :rules="addFormRules" ref="addRolesForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesUser">确 定</el-button>
      </span>
    </el-dialog>
<!--    分配权限-->
    <el-dialog title="分配权限" :visible.sync="SetRightDialogVisible" width="50%" @close="SetRightDialogVisibleClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      rolesList: [],
      editDialogVisible: false,
      addDialogVisible: false,
      roleNameRules: {
        roleName: [
          { required: true, message: '请输入角色名字', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '输入的范围是 3 ~ 10 为字符',
            triggetr: 'nlur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 5,
            max: 20,
            message: '输入的范围是 5 ~ 20 为字符',
            triggetr: 'nlur'
          }
        ]
      },
      addRolesForm: {

      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名字', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '输入的范围是 3 ~ 10 为字符',
            triggetr: 'nlur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 5,
            max: 20,
            message: '输入的范围是 5 ~ 20 为字符',
            triggetr: 'nlur'
          }
        ]
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名字', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '输入的范围是 3 ~ 10 为字符',
            triggetr: 'nlur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 5,
            max: 20,
            message: '输入的范围是 5 ~ 20 为字符',
            triggetr: 'nlur'
          }
        ]
      },
      editRolesForm: {},
      SetRightDialogVisible: false,
      // 树形控件的绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件 -> 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配权限的角色的ID
      rolesId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      } else {
        this.rolesList = res.data
        this.$message.success('获取角色列表成功')
      }
    },
    async showRoleDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('查询用户角色失败')
      } else {
        this.editRolesForm = res.data
        console.log(this.editRolesForm)
        this.editDialogVisible = true
      }
    },
    editFormInfo () {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        this.$http.put('roles/' + this.editRolesForm.roleId, {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc
        }).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('修改角色失败!')
          }
          this.$message.success('修改角色成功!')
          this.getRolesList()
        })
        this.editDialogVisible = false
      })
    },
    async removeRole (id) {
      const confirmRusult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRusult !== 'confirm') {
        return this.$message.info('已取消该删除操作')
      }
      this.$http.delete('roles/' + id).then(res => {
        const { data: response } = res
        // console.log(response)
        if (response.meta.status !== 200) {
          return this.$message.error('该用户删除失败')
        }
        this.$message.success('该用户已经删除')
        this.getRolesList()
      })
    },
    // 添加角色
    addRolesUser () {
      this.$refs.addRolesForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败!')
        }
        this.$message.success('添加角色成功!')
        this.getRolesList()
        this.addDialogVisible = false
      })
      // console.log(this.addRolesForm)
    },
    // 清空添加角色对话框
    addDislogClosed () {
      this.$refs.addRolesForm.resetFields()
    },
    async removeRightByid (role, rightid) {
      const confirmResult = await this.$confirm('此操作将永久删除文件，是否继续？', '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
      if (confirmResult !== 'confirm') {
        this.$message.info('你取消了删除')
      } else {
        this.$message.info('你确认了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('未删除')
      } else {
        this.$message.success('删除成功')
        // this.getRolesList()
        role.children = res.data
      }
    },
    async showSetRightDialog (roles) {
      this.rolesId = roles.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败!')
      }
      // 获取到的权限数据保存
      this.rightsList = res.data
      console.log(this.rightsList)
      // 递归获取三级节点
      this.getLeafKeys(roles, this.defKeys)
      this.SetRightDialogVisible = true
    },
    // 递归的形式,获取角色下所有的三级权限的id,并保存到 defKeys数组中
    getLeafKeys (node, arr) {
      // 如果当前node没有children属性则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框的关闭事件
    SetRightDialogVisibleClosed () {
      // 清空 defkeys 数组  避免累积
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.SetRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
